﻿using SqlSugar;
using System.Data;
using System.Data.SqlClient;

namespace Maltose.Data
{
    /// <summary>
    /// 数据库基础访问类
    /// </summary>
    public class DataBaseService
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        public string DbConnectionString { get; set; }

        /// <summary>
        /// SqlSugar上下文
        /// </summary>
        public SqlSugarClient DbContext
        {
            get
            {
                return new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = DbConnectionString,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                });
            }
        }

        /// <summary>
        /// 数据连接对象 Dapper使用连接接口
        /// </summary>
        public IDbConnection IConnection
        {
            get
            {
                var conn = new SqlConnection(DbConnectionString);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                return conn;
            }
        }

        /// <summary>
        /// 原生数据连接对象
        /// </summary>
        public SqlConnection Connection
        {
            get
            {
                var conn = new SqlConnection(DbConnectionString);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                return conn;
            }
        }


        /// <summary>
        ///  数据库基础访问类
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        public DataBaseService(string connectionString)
        {
            DbConnectionString = connectionString;
        }

        /// <summary>
        /// 数据库基础访问类
        /// </summary>
        /// <param name="dataBase">选择数据库</param>
        public DataBaseService(DataBase dataBase = DataBase.Default)
        {
            var key = $"DbConnectionStrings:{dataBase}";
            DbConnectionString = DataServiceConfig.Configuration.GetSection(key).Value;
        }
    }
}
